import axios from "axios"
// import { ElMessage } from "element-plus"
import { useUserStoreWithOut } from "@/store/modules/user"
import { ElMessage } from "element-plus"
// import { useReflesh } from "@/hooks/useReflesh"
// import { useRouter } from "vue-router"
// import { refreshTokenApi } from "@/api/login"

// import { refreshTokenApi } from "@/api/login"
const instance: any = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
})

// 请求拦截器
instance.interceptors.request.use(
  (config: any) => {
    const userStore = useUserStoreWithOut()
    config.headers.Authorization = userStore.getAccessToken
    // console.log(userStore.getAccessToken);
    // console.log(config);
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

// 刷新token
const refreshToken = async () => {
  const userStore = useUserStoreWithOut()
  const refresh_token = userStore.getRefreshToken;
  if (!refresh_token) {
    Promise.reject("长token失效");
  }

  // 这里会等到并发的请求都执行完之后再执行
  const res = await axios.get(`http://localhost:3000/auth/refreshToken`, {
    params: {
      refresh_token
    }
  })

  return res;
};


// 是否还需要刷新token的标识
let refreshing = false;
// 存储未完成的请求
const task: any[] = [];

// 响应拦截器
instance.interceptors.response.use(
  (response: any) => {
    return response.data
  },
  async (error: any) => {
    console.log(11, error);
    const { data, config } = error?.response;

    // 如果正在刷新token，则将失败的请求挂起,
    // 存入task中等待刷新token完成在全部执行出来
    if (refreshing) {
      return new Promise((resolve) => {
        task.push({
          config,
          resolve,
        });
      });
    }

    // 如果是登录过期并且请求的地址不是 /user/refresh，就调用refreshToken
    if (data.statusCode === 401 && config.url !== "/auth/refreshToken") {

      // 此时需要刷新了
      refreshing = true;
      try {
        const res = await refreshToken();

        // 重新发送请求
        task.forEach((item) => {
          item.resolve(instance.request(item.config));
        });
        const userStore = useUserStoreWithOut()
        userStore.setAccessToken(res.data.access_token)
        userStore.setRefreshToken(res.data.refresh_token)

        // 刷新token成功
        refreshing = false;
        return instance.request(config);
      } catch (error) {
        // refreshToken失败，跳转到登录页
        // ......
      }
    }
    if (error.status === 403) {
      ElMessage.error(error.response.data.description + error.config.url + "接口")
    }
    return Promise.resolve(error);
  }
)

export default {
  get: (url: string, params?: any) => instance.get(url, { params }),
  post: (url: string, params: any) => instance.post(url, params),
}